package org.msgcenter.mc.actor;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.json.JSONUtil;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.eventbus.MessageConsumer;
import lombok.extern.slf4j.Slf4j;
import org.msgcenter.mc.common.ConvertUtil;
import org.msgcenter.mc.ds.*;

@Slf4j
public class MsgDispatcherActor extends AbstractVerticle {

  // 站点消息统计
  private int siteMsgCount = 0;

  // 企业微信消息统计
  private int companyWeChatCount = 0;

  private EventBus eb;

  @Override
  public void start(Promise<Void> startPromise) throws Exception {
    super.start(startPromise);

    eb = vertx.eventBus();

    onDispatch();
  }

  private void onDispatch() {
    MessageConsumer<String> consumer = eb.consumer("service.dispatch");

    consumer.handler(payload -> {
      RequestMsg req = JSONUtil.toBean(payload.body(), new TypeReference<>() {
      }, true);
      eb.publish("db.post.add_request_msg", JSONUtil.toJsonStr(req));

      PushStateMsg stateMsg = ConvertUtil.requestMsgToPushStateMsg(req);
      stateMsg.setChannelType(req.getChannelType());
      eb.publish("db.post.add_push_state", JSONUtil.toJsonStr(stateMsg));

      // 基础站点消息
      if (req.getChannelType().equals(SendMsgHelpers.BASE_SITE_MSG)) {
        SiteMsg siteMsg = ConvertUtil.requestMsgToSiteMsg(req);
        // 保存消息记录
        eb.publish("service.push_msg.site_msg", JSONUtil.toJsonStr(siteMsg));
        ++siteMsgCount;
      }

      // 基础企业微信消息
      if (req.getChannelType().equals(SendMsgHelpers.BASE_COMPANY_WECHAT_MSG)) {
        CompanyWechatMsg msg = ConvertUtil.requestMsgToCompanyWechatMsg(req);
        eb.publish("service.push_msg.company_wechat_msg", JSONUtil.toJsonStr(msg));
        ++ companyWeChatCount;
      }
    });
  }

  @Override
  public void stop(Promise<Void> stopPromise) throws Exception {
    super.stop(stopPromise);
  }
}
